package com.kongxx.wicketstudy.tutorial.user.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.kongxx.wicketstudy.tutorial.user.model.User;
import com.kongxx.wicketstudy.tutorial.user.service.UserService;

public class UserServiceImpl implements UserService, Serializable {
	private static final long serialVersionUID = 1L;
	private static List users;
	
	static {
		users = new ArrayList();
		users.add(new User("0", "Admin", "Admin", "---"));
		users.add(new User("1", "user1", "password1", "---"));
		users.add(new User("2", "user2", "password2", "---"));
		users.add(new User("3", "user3", "password3", "---"));
		users.add(new User("4", "user4", "password4", "---"));
		users.add(new User("5", "user5", "password5", "---"));
	}
	
	public List list() {
		return users;
	}

	public List list(final int first, final int size) {
		return users.subList(first, first + size);
	}
	
	public List list(final int first, final int size, final String sort, final String order) {
		List sortedUsers = new ArrayList(users);
		if (sort.equals("id")) {
			Collections.sort(sortedUsers, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					User user1 = (User) arg0;
					User user2 = (User) arg1;
					int result = user1.getId().compareTo(user2.getId());
					return (order.equalsIgnoreCase("asc")) ? result : -result;
				}
			});
		} else if (sort.equals("username")) {
			Collections.sort(sortedUsers, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					User user1 = (User) arg0;
					User user2 = (User) arg1;
					int result = user1.getUsername().compareTo(user2.getUsername());
					return (order.equalsIgnoreCase("asc")) ? result : -result;
				}
			});
		}
		System.out.println(sortedUsers);
		return sortedUsers.subList(first, first + size);
	}
	
	public User find(String id) {
		for (int i = 0; i < users.size(); i++) {
			User user = (User)users.get(i);
			if(id.equals(user.getId())) {
				return user;
			} 
		}
		return null;
	}
		
	public void add(User user) {
		users.add(user);
	}

	public void modify(User user) {
		users.add(user);
	}

	public void delete(User user) {
		users.remove(user);
	}

}
